<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Requests\Api\v1\RechargeRequest;
use App\Http\Requests\Api\v1\RechargeCodeRequest;
use App\Http\Resources\FriendResource;
use App\Http\Resources\OrderResource;
use App\Http\Resources\TaskResource;
use App\Jobs\RechargeExpireJob;
use App\Models\Configuration;
use App\Models\PaymentThirdCode;
use App\Models\PaymentThirdPay;
use App\Models\RechargeAddress;
use App\Models\User;
use App\Service\Pay\PayFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use App\Models\Order;
use Carbon\Carbon;

class RechargeController extends Controller
{
    /**
     * 充值记录
     * @param RechargeRequest $request
     * @param Order $order
     * @return JsonResponse
     */
    public function index(RechargeRequest $request, Order $order): JsonResponse
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $recharge = $order->list($request->user(), Order::RECHARGE, $this->paging($page, $limit), $limit, $request->get('date', ''));
        return $this->success(OrderResource::collection($recharge));
    }


    /**
     * 充值
     * @param RechargeRequest $request
     * @return JsonResponse|object  //: JsonResponse
     */
    public function store(RechargeRequest $request)
    {
        $user = $request->user();
        if (!Configuration::getItem('recharge_switch')) {
            return $this->fail(40042, trans('error.40042'));
        }
        $amount = round($request->get('amount'), 4);

        //查用户有没有进行中的订单
        $order = Order::query()
            ->select('platform', 'created_at', 'id', 'payment_no', 'amount')
            ->where('user_id', '=', $user->id)
            ->where('type', '=', Order::RECHARGE)
            ->where('amount', '>=', $amount)
            ->where('amount', '<', $amount + 1)
            ->where('state', Order::PENDING)
            ->where('created_at', '>', Carbon::now()->subSeconds(Configuration::getItem('recharge_address_time')))
            ->first();
        if ($order) {
            $order->amount = rtrim(rtrim($order->amount, '0'), '.');
            $time = time() - $order->created_at->timestamp;
            $order->recharge_payment_time = Configuration::getItem('recharge_payment_time') - $time;
            return $this->success($order, Response::HTTP_OK, trans('error.40004'));
        }

        //收款地址,,验证是否占用
        $recharge = self::getRechargeAddress($amount);
        if (!$recharge) {
            return $this->fail(20004, trans('error.20004'));
        }
        //生成订单
        $order = $user->order()->create([
            'platform' => 'trc',
            'payment_third_pay_id' => $recharge['address_id'],
            'amount' => $recharge['amount'],
            'payment_no' => $recharge['address'],
            'no' => only_code(),
            'type' => Order::RECHARGE
        ]);

        if ($order) {
            $order->recharge_payment_time = Configuration::getItem('recharge_payment_time');
            //加入超时队列
            RechargeExpireJob::dispatch($order)->delay(Configuration::getItem('recharge_address_time'));
            return $this->success($order, Response::HTTP_OK, trans('error.40004'));
        }
        return $this->fail(40001, trans('error.40001'));
    }


    private function getRechargeAddress($amount)
    {
        $addresses = RechargeAddress::query()->where('state', true)
            ->where(function ($query) use ($amount) {
                $query->orWhere(function ($sql) use ($amount) {
                    $sql->where('lower', '<=', $amount)->where('upper', '>=', $amount);
                });
                $query->orWhere(function ($sql) {
                    $sql->where('lower', '=', 0)->where('upper', '=', 0);
                });
            })
            ->whereRaw('(total = 0 or total > recharge_total)')
            ->inRandomOrder()->get();
        if (!count($addresses)) {
            return false;
        }

        foreach ($addresses as $address) {
            $order = Order::query()
                ->where('type', '=', Order::RECHARGE)
                ->where('payment_third_pay_id', $address->id)
                ->where('amount', $amount)
                ->where('state', Order::PENDING)
                ->where('created_at', '>', Carbon::now()->subSeconds(Configuration::getItem('recharge_address_time')))
                ->first();
            if (!$order) {
                $data['address_id'] = $address->id;
                $data['address'] = $address->address;
                $data['amount'] = $amount;
                return $data;
            }
        }
        //$amount = $amount + rand(1,5)/100;
        $amount = $amount + 0.01;
        return self::getRechargeAddress($amount);
    }


    /**
     * 确认支付--未完成 未使用
     * @param RechargeRequest $request
     * @return JsonResponse|object
     */
    public function update(Order $order, RechargeRequest $request): JsonResponse
    {
        $recharge_address = $request->get('recharge_address');

        if (!$recharge_address || strlen($recharge_address) != '64') {
            $this->errorResponse(Response::HTTP_OK, trans('error.10009'), 10009);
        }
        if (Order::query()->where('payment_no', '=', $recharge_address)->first()) {
            $this->errorResponse(Response::HTTP_OK, trans('error.10009'), 10009);
        }

        $order->payment_no = $recharge_address;
        $order->save();

        return $this->success('sd');
    }


    //充值配置
    public function switch()
    {
        $data = [
            'recharge_switch' => (bool)Configuration::getItem('recharge_switch'),
            'recharge_trc_address' => Configuration::getItem('recharge_trc_address')
        ];
        return $this->success($data);
    }


    public function show(int $id)
    {
        //$order = Order::query()->where('id'.)
        return $this->success(new OrderResource(Order::getOrder($id)));
    }




    /**
     * 充值--三方支付
     * @param RechargeRequest $request
     * @return JsonResponse|object
     */
    public function other(RechargeRequest $request): JsonResponse
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        if (Configuration::getItem('recharge_switch') != 2) {
            return $this->fail(40042, trans('error.40042'));
        }

        $code_id = $request->get('code_id');
        if($code_id){
            $payment_third_code = PaymentThirdCode::query()->open()->whereHas('payment', function ($q) {
                $q->open()->pay(PaymentThirdPay::PAY_OPEN);
            })->with(['payment'])->where('id',$code_id)->first();
        }else{
            $payment_third_code = PaymentThirdCode::query()->open()->whereHas('payment', function ($q) {
                $q->open()->pay(PaymentThirdPay::PAY_OPEN);
            })->with(['payment'])->first();
        }

        if (!$payment_third_code || !$payment_third_code->payment) {
            $this->errorResponse(Response::HTTP_OK, trans('error.60000'), 60000);
        }
        $amount = $request->get('amount');

        if ($amount > $payment_third_code->upper) {
            return $this->fail(60012, sprintf(trans('error.60012'), $payment_third_code->upper));
        }
        if ($amount < $payment_third_code->lower) {
            return $this->fail(60011, sprintf(trans('error.60011'), $payment_third_code->lower));
        }
        //生成订单
        $order = $user->order()->create([
            'platform' => $payment_third_code->payment->server_name,
            'payment_third_pay_id' => $payment_third_code->id,
            'amount' => $amount,
            'no' => only_code(),
            'type' => Order::RECHARGE
        ]);

        $attach = [];
        // 生成远程订单
        $url = PayFactory::service(ucfirst($payment_third_code->payment->server_name), $order)->recharge($attach);
        if ($url) {
            return $this->success([
                'url' => $url,
                're_url' => config('ThirdPay.redirect_url')
            ]);
        }
        return $this->fail(40050, trans('error.40050'));
    }



}
